import type { Directive, DirectiveBinding } from "vue";

/**
 * input 限制小数
 */

export const inputLimit: Directive = {
	mounted(el, binding: DirectiveBinding) {
		const { value } = binding;
		console.log(value);
		//digit:1=一位小数，2=两位小数，10=0位小数能输入o 正数，11=0位小数不能输入o 正数
		const digit = value != null || value != undefined ? value : 2;
		const input = el.querySelector("input");
		input.setAttribute("type", "text");
		input.addEventListener("input", (val: any) => {
			const {
				target: { value }
			} = val;
			console.log(val.target.value);
			if (digit == 10) {
				val.target.value = value.replace(/^0+(\d)|[^\d]+/g, "");
			} else if (digit == 11) {
				val.target.value = value.replace(/^(0+)|[^\d]+/g, "");
			} else if (digit == 1) {
				val.target.value = value
					.replace(/^0[0-9]+/, (val: any[]) => val[1])
					.replace(/^(\.)+/, "")
					.replace(/[^\d.]/g, "")
					.replace(/\.{2,}/g, ".")
					.replace(/^(\-)*(\d+)\.(\d).*$/, "$1$2.$3");
			} else {
				val.target.value = value
					.replace(/^0[0-9]+/, (val: any[]) => val[1])
					.replace(/^(\.)+/, "")
					.replace(/[^\d.]/g, "")
					.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
			}
		});
	},
	unmounted(el) {
		const input = el.querySelector("input");
		input.addEventListener("input", () => {});
	}
};
